<template>
  <div class="home-container">
    <!-- 顶部轮播图 -->
    <div class="banner-section">
      <el-carousel height="400px">
        <el-carousel-item v-for="item in banners" :key="item.id">
          <div class="banner-item" :style="{ backgroundImage: `url(${item.image})` }">
            <div class="banner-content">
              <h2>{{ item.title }}</h2>
              <p>{{ item.desc }}</p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 左侧边栏 - AI助手 -->
      <div class="sidebar">
        <ai-assistant class="ai-assistant-wrapper"></ai-assistant>
      </div>
      
      <!-- 右侧主内容区 -->
      <div class="page-container">
        <!-- 课程推荐 -->
        <div class="section">
          <div class="section-header">
            <h2 class="section-title">推荐课程</h2>
            <el-button type="text" @click="goToCourses" class="more-link">查看更多</el-button>
          </div>
          <div class="course-list">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-for="course in recommendCourses" :key="course.id">
                <div class="blog-card course-card">
                  <div class="course-cover">
                    <img :src="course.cover" :alt="course.title">
                  </div>
                  <div class="blog-card-content">
                    <h3 class="course-title">{{ course.title }}</h3>
                    <p class="course-teacher">授课教师：{{ course.teacher }}</p>
                  </div>
                  <div class="blog-card-footer">
                    <span class="course-students">{{ course.studentCount || 0 }}人学习</span>
                    <router-link :to="`/course/${course.id}`" class="btn-primary">查看详情</router-link>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 最新资料 -->
        <div class="section">
          <div class="section-header">
            <h2 class="section-title">最新资料</h2>
            <el-button type="text" @click="goToMaterials" class="more-link">查看更多</el-button>
          </div>
          <div class="material-list" v-loading="materialsLoading">
            <div class="blog-card" v-for="material in latestMaterials" :key="material.id">
              <div class="blog-card-content">
                <div class="material-info">
                  <h3 class="material-title">{{ material.title }}</h3>
                  <div class="material-meta">
                    <span class="material-type">
                      <i :class="getFileIcon(material.type)"></i> {{ material.type.toUpperCase() }}
                    </span>
                    <span class="material-size">{{ material.size }}</span>
                  </div>
                </div>
              </div>
              <div class="blog-card-footer">
                <span class="material-date">{{ material.createTime }}</span>
                <router-link :to="`/material/${material.id}`" class="btn-primary">查看详情</router-link>
              </div>
            </div>
            <!-- 空状态 -->
            <el-empty v-if="latestMaterials.length === 0 && !materialsLoading" description="暂无最新资料"></el-empty>
          </div>
        </div>

        <!-- 近期考试 -->
        <div class="section">
          <div class="section-header">
            <h2 class="section-title">近期考试</h2>
            <el-button type="text" @click="goToExams" class="more-link">查看更多</el-button>
          </div>
          <div class="exam-list" v-loading="examsLoading">
            <div class="blog-card" v-for="exam in upcomingExams" :key="exam.id">
              <div class="blog-card-header">
                <h3 class="exam-title">{{ exam.title }}</h3>
                <span class="exam-status" :class="getStatusClass(exam.status)">{{ getStatusText(exam.status) }}</span>
              </div>
              <div class="blog-card-content">
                <div class="exam-info">
                  <p><i class="el-icon-time"></i> 开始时间：{{ exam.startTime }}</p>
                  <p><i class="el-icon-timer"></i> 考试时长：{{ exam.duration }}分钟</p>
                  <p v-if="exam.subjectName"><i class="el-icon-notebook-2"></i> 考试科目：{{ exam.subjectName }}</p>
                  
                  <!-- 倒计时 -->
                  <div v-if="exam.status === 'upcoming'" class="countdown">
                    <span class="countdown-label">距离开始还有：</span>
                    <span class="countdown-time">{{ exam.countdown || '计算中...' }}</span>
                  </div>
                  <div v-else-if="exam.status === 'ongoing'" class="countdown ongoing">
                    <span class="countdown-label">正在进行中：</span>
                    <span class="countdown-time">已开始 {{ exam.elapsedTime || '' }}</span>
                  </div>
                </div>
              </div>
              <div class="blog-card-footer">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="goToExamDetail(exam.id)"
                  :disabled="exam.status === 'completed'">
                  {{ getExamButtonText(exam.status) }}
                </el-button>
              </div>
            </div>
            
            <!-- 空状态 -->
            <el-empty v-if="upcomingExams.length === 0 && !examsLoading" description="暂无近期考试"></el-empty>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AiAssistant from '@/components/AiAssistant.vue'

export default {
  name: 'Home',
  components: {
    AiAssistant
  },
  data() {
    return {
      banners: [
        {
          id: 1,
          title: '欢迎来到教育平台',
          desc: '在这里开启你的学习之旅',
          image: 'https://picsum.photos/1200/400?random=1'
        },
        {
          id: 2,
          title: '随时随地学习',
          desc: '丰富的课程资源，助你成长',
          image: 'https://picsum.photos/1200/400?random=2'
        },
        {
          id: 3,
          title: '在线考试系统',
          desc: '便捷的考试体验，实时查看成绩',
          image: 'https://picsum.photos/1200/400?random=3'
        }
      ],
      recommendCourses: [],
      latestMaterials: [],
      upcomingExams: [],
      materialsLoading: false,
      examsLoading: false,
      countdownTimer: null
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
    // 启动倒计时定时器
    this.startCountdown()
  },
  beforeDestroy() {
    // 清除定时器
    this.clearCountdown()
  },
  methods: {
    fetchData() {
      // 获取推荐课程
      this.$store.dispatch('getCourses').then(courses => {
        this.recommendCourses = courses
      })
      
      // 获取最新资料
      this.materialsLoading = true
      this.$store.dispatch('getMaterials').then(materials => {
        this.latestMaterials = materials
        this.materialsLoading = false
      })
      
      // 获取近期考试
      this.examsLoading = true
      this.$store.dispatch('getExams').then(exams => {
        this.upcomingExams = exams
        this.examsLoading = false
        this.updateCountdown() // 初始化倒计时
      }).catch(() => {
        this.examsLoading = false
      })
    },
    getStatusClass(status) {
      switch (status) {
        case 'upcoming':
          return 'tag tag-blue'
        case 'ongoing':
          return 'tag tag-green'
        case 'completed':
          return 'tag tag-orange'
        default:
          return 'tag tag-info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 'upcoming':
          return '即将开始'
        case 'ongoing':
          return '进行中'
        case 'completed':
          return '已完成'
        default:
          return '未知'
      }
    },
    getFileIcon(type) {
      // 根据文件类型返回对应的图标
      const typeMap = {
        'pdf': 'el-icon-document',
        'doc': 'el-icon-document-word',
        'docx': 'el-icon-document-word',
        'xls': 'el-icon-document-excel',
        'xlsx': 'el-icon-document-excel',
        'ppt': 'el-icon-document-ppt',
        'pptx': 'el-icon-document-ppt',
        'txt': 'el-icon-document-text',
        'jpg': 'el-icon-picture',
        'jpeg': 'el-icon-picture',
        'png': 'el-icon-picture',
        'gif': 'el-icon-picture',
        'mp4': 'el-icon-video-play',
        'mp3': 'el-icon-headset',
        'zip': 'el-icon-folder',
        'rar': 'el-icon-folder'
      }
      
      return typeMap[type.toLowerCase()] || 'el-icon-document'
    },
    getExamButtonText(status) {
      switch (status) {
        case 'upcoming':
          return '查看详情'
        case 'ongoing':
          return '立即参加'
        case 'completed':
          return '查看结果'
        default:
          return '查看详情'
      }
    },
    goToCourses() {
      this.$router.push('/courses')
    },
    goToMaterials() {
      this.$router.push('/materials')
    },
    goToExams() {
      this.$router.push('/exams')
    },
    goToExamDetail(examId) {
      this.$router.push(`/exam/${examId}`)
    },
    startCountdown() {
      this.countdownTimer = setInterval(() => {
        this.updateCountdown()
      }, 1000)
    },
    clearCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
    },
    updateCountdown() {
      const now = new Date()
      
      this.upcomingExams.forEach(exam => {
        const startTime = new Date(exam.rawStartTime || exam.startTime)
        const endTime = new Date(startTime.getTime() + (exam.duration * 60 * 1000))
        
        if (now < startTime) {
          // 未开始，显示倒计时
          const diff = startTime - now
          exam.countdown = this.formatDuration(diff)
          exam.status = 'upcoming'
        } else if (now >= startTime && now <= endTime) {
          // 进行中，显示已经开始多久
          const elapsed = now - startTime
          exam.elapsedTime = this.formatDuration(elapsed)
          exam.status = 'ongoing'
        } else {
          // 已结束
          exam.status = 'completed'
        }
      })
    },
    formatDuration(ms) {
      const totalSeconds = Math.floor(ms / 1000)
      const days = Math.floor(totalSeconds / (3600 * 24))
      const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600)
      const minutes = Math.floor((totalSeconds % 3600) / 60)
      const seconds = totalSeconds % 60
      
      let result = ''
      if (days > 0) result += `${days}天 `
      if (hours > 0 || days > 0) result += `${this.padZero(hours)}时 `
      result += `${this.padZero(minutes)}分 ${this.padZero(seconds)}秒`
      
      return result
    },
    padZero(num) {
      return num < 10 ? `0${num}` : num
    }
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  padding-bottom: 40px;
}

.banner-section {
  margin-bottom: 30px;
  
  .banner-item {
    height: 100%;
    background-size: cover;
    background-position: center;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.3);
    }
  }
  
  .banner-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: #fff;
    width: 80%;
    
    h2 {
      font-size: 32px;
      margin-bottom: 15px;
      font-weight: bold;
    }
    
    p {
      font-size: 18px;
      margin: 0;
    }
  }
}

.main-content {
  display: flex;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 15px;
}

.sidebar {
  width: 320px;
  padding-right: 30px;
  flex-shrink: 0;
  margin-left: -15px;
}

.page-container {
  flex: 1;
  padding: 0 15px;
}

.ai-assistant-wrapper {
  position: sticky;
  top: 80px;
  min-height: 500px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
  position: relative;
  padding-left: 15px;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 5px;
    height: 20px;
    background-color: #409EFF;
    border-radius: 2px;
  }
}

.more-link {
  color: #409EFF;
  text-decoration: none;
  font-size: 14px;
  
  &:hover {
    text-decoration: underline;
  }
}

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  
  .course-cover {
    height: 150px;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
    }
  }
  
  &:hover .course-cover img {
    transform: scale(1.05);
  }
  
  .course-title {
    font-size: 18px;
    margin: 0 0 10px;
    color: #303133;
  }
  
  .course-teacher {
    color: #606266;
    margin: 0;
  }
  
  .course-students {
    color: #909399;
    font-size: 14px;
  }
}

.course-list {
  .el-row {
    margin-left: -10px;
    margin-right: -10px;
  }
  
  .el-col {
    padding-left: 10px;
    padding-right: 10px;
  }
}

.material-list, .exam-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.material-title, .exam-title {
  font-size: 16px;
  margin: 0 0 10px;
  color: #303133;
}

.material-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #606266;
}

.material-type {
  display: inline-flex;
  align-items: center;
  
  i {
    margin-right: 5px;
  }
}

.material-date {
  color: #909399;
  font-size: 14px;
}

.exam-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  min-height: 200px;
}

.blog-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 15px 0 rgba(0, 0, 0, 0.15);
  }
  
  .blog-card-header {
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .blog-card-content {
    padding: 15px;
    flex: 1;
  }
  
  .blog-card-footer {
    padding: 15px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
  }
}

.exam-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.tag-blue {
  background-color: #409EFF;
}

.tag-green {
  background-color: #67C23A;
}

.tag-orange {
  background-color: #E6A23C;
}

.tag-info {
  background-color: #909399;
}

.exam-info {
  p {
    margin: 5px 0;
    color: #606266;
    
    i {
      margin-right: 5px;
    }
  }
}

.countdown {
  margin-top: 10px;
  background-color: #ecf5ff;
  padding: 8px 12px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  &.ongoing {
    background-color: #f0f9eb;
  }
  
  .countdown-label {
    font-size: 12px;
    color: #606266;
  }
  
  .countdown-time {
    font-size: 14px;
    font-weight: bold;
    color: #409EFF;
  }
}

.ongoing .countdown-time {
  color: #67C23A;
}

@media (max-width: 1400px) {
  .material-list, .exam-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 1200px) {
  .material-list, .exam-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
    padding-right: 0;
    margin-left: 0;
  }
  
  .page-container {
    padding: 0;
  }
  
  .ai-assistant-wrapper {
    position: static;
    min-height: 400px;
  }
}

@media (max-width: 768px) {
  .banner-content {
    h2 {
      font-size: 24px;
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .material-list, .exam-list {
    grid-template-columns: 1fr;
  }
}
</style> 